package com.mfsoft.camera;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;


import com.mfsoft.net.MyFunctions_THI;
import com.mfsoft.utilities.Utility;

public class UpdateMyProfileActivity extends Activity {
	Calendar lich = Calendar.getInstance();
	SimpleDateFormat sdf;
	EditText edtdangnhap, edtdiachimail, edtmatkhaumoi, edtOldPasswrod,
			edtconfirmpassword;
	Button btnUpdateMyProfile;
	private ImageButton btnBirthday;
	private TextView tvBirthday, tvgender;
	int typengay;
	RadioGroup radioGroup;
	RadioButton rdbnam, rdbnu;
	MyFunctions_THI myFunctions_THI;
	String prefname = "my_data";
	Context context;
	private SharedPreferences preferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update_my_profile);

		btnBirthday = (ImageButton) findViewById(R.id.btnbirthday);
		edtdangnhap = (EditText) findViewById(R.id.edtdangnhap);
		edtdiachimail = (EditText) findViewById(R.id.edtdaichimail);
		edtOldPasswrod = (EditText) findViewById(R.id.edtOldPasswrod);
		edtmatkhaumoi = (EditText) findViewById(R.id.edtmatkhaumoi);
		edtconfirmpassword = (EditText) findViewById(R.id.edtconfirmpassword);
		tvBirthday = (TextView) findViewById(R.id.txtbirthdayfill);
		btnUpdateMyProfile = (Button) findViewById(R.id.btncapnhat);
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		sdf.setLenient(true);
		radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
		rdbnam = (RadioButton) findViewById(R.id.rdbnam);
		rdbnu = (RadioButton) findViewById(R.id.rdbnu);
		preferences = getSharedPreferences(prefname, context.MODE_PRIVATE);
		String username = preferences.getString("username", "");
		String gmail = preferences.getString("gmail", "");
		String gender = preferences.getString("gender", "");
		String birthday = preferences.getString("birthday", "");
		edtdangnhap.setText(username);
		edtdiachimail.setText(gmail);
		if (gender == "1") {
			rdbnam.setChecked(true);
		} else {
			rdbnu.setChecked(false);
		}
		tvBirthday.setText(birthday);
		btnBirthday.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				typengay = 1;
				showdate();
			}
		});
		btnUpdateMyProfile.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				UpdateMyProfile updateMyProfile = new UpdateMyProfile();
				if (updateMyProfile.getStatus() == AsyncTask.Status.PENDING) {

					updateMyProfile.execute();

				}
				Intent i = new Intent(getApplicationContext(),
						MainActivity.class);
				startActivity(i);
				finish();
			}
		});

	}

	class UpdateMyProfile extends AsyncTask<Void, Void, String> {

		String tendangnhap, diachiemail, matkhaumoi, OldPasswrod,
				confirmpassword, gender, ngaysinh;
		MyFunctions_THI myfunctions_thi;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			final ProgressDialog dialog = ProgressDialog.show(
					UpdateMyProfileActivity.this, "Doing Update",
					"Please wait...", true);
			new Thread(new Runnable() {
				public void run() {
					try {
						// ---simulate doing something lengthy---
						Thread.sleep(5000);
						// ---dismiss the dialog---
						dialog.dismiss();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();

		}

		@Override
		protected String doInBackground(Void... arg0) {
			// TODO Auto-generated method stub

			tendangnhap = edtdangnhap.getText().toString();
			diachiemail = edtdiachimail.getText().toString();
			OldPasswrod = edtOldPasswrod.getText().toString();
			matkhaumoi = edtmatkhaumoi.getText().toString();
			confirmpassword = edtconfirmpassword.getText().toString();
			OldPasswrod = Utility.md5(OldPasswrod);
			matkhaumoi = Utility.md5(matkhaumoi);
			if (rdbnam.isChecked() == true) {
				gender = "1";
				tvgender.setText(R.string.nam);
			} else {
				gender = "0";
				tvgender.setText(R.string.nu);
			}
			ngaysinh = tvBirthday.getText().toString();
			String thanhcong = "-1";
			if (matkhaumoi.toString().equals("")) {
				try {
					myfunctions_thi = new MyFunctions_THI(
							getApplicationContext());
					JSONObject jsonObject = myfunctions_thi.NoUpdateMyProfile(
							tendangnhap, diachiemail, OldPasswrod, gender,
							ngaysinh);
					return jsonObject.toString();

				} catch (Exception e) {
					Log.d("loi",
							"Khong tao duoc json khong dang ky duoc"
									+ e.toString());
				}
				return thanhcong;
			} else {
				if (checkPassWord()) {
					try {
						myfunctions_thi = new MyFunctions_THI(
								getApplicationContext());
						JSONObject jsonObject = myfunctions_thi
								.UpdateMyProfile(tendangnhap, diachiemail,
										matkhaumoi, gender, ngaysinh);
						return jsonObject.toString();

					} catch (Exception e) {
						Log.d("loi", "Khong tao duoc json khong dang ky duoc"
								+ e.toString());
					}
					return thanhcong;
				} else {
					CheckOldPassWord(tendangnhap, OldPasswrod);

				}
			}
			return thanhcong;

		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// tao doi tuong getSharedPreferences
			SharedPreferences pre = getSharedPreferences(prefname, MODE_PRIVATE);
			// tao doi tuong Editor de luu thay doi
			SharedPreferences.Editor editor = pre.edit();
			try {

				if (diachiemail != preferences.getString("gmail", "")) {
					editor.putString("diachiemail", diachiemail);
					editor.commit();
				} else

				if (gender != preferences.getString("gender", "")) {
					editor.putString("gender", gender);
					editor.commit();
				} else if (ngaysinh != preferences.getString("ngaysinh",
						ngaysinh)) {
					editor.putString("ngaysinh", ngaysinh);
					editor.commit();
				} else {

					editor.putString("diachiemail", diachiemail);
					editor.putString("pasword", matkhaumoi);
					editor.putString("gender", gender);
					editor.putString("ngaysinh", ngaysinh);
					editor.commit();
				}

			} catch (Exception e) {

			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.update_my_profile, menu);
		return true;
	}

	public void removeSharedPreferences() {

		SharedPreferences pre = context.getSharedPreferences(prefname,
				context.MODE_PRIVATE);
		// tạo đối tượng Editor để lưu thay đổi
		SharedPreferences.Editor edit = pre.edit();
		// SharedPreferences preferences = null;
		edit = pre.edit();
		edit.remove("username");
		edit.remove("gmail");
		edit.remove("birthday");
		edit.remove("gender");
		edit.commit();
	}

	private boolean validateEmailAddress(String emailAddress) {

		if (Build.VERSION.SDK_INT >= 8) {
			return android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress)
					.matches();
		}

		Pattern pattern;
		Matcher matcher;
		String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(EMAIL_PATTERN);
		matcher = pattern.matcher(emailAddress);

		return matcher.matches();

	}

	// kiem tra Oldpassword
	public boolean CheckOldPassWord(String username, String Oldpassword) {

		boolean isOk = true;
		MyFunctions_THI myfunction_thi;
		String thanhcong = null;
		username = edtdangnhap.getText().toString();
		Oldpassword = edtOldPasswrod.getText().toString();
		Oldpassword = Utility.md5(Oldpassword);
		try {
			{
				JSONObject jsonobject;

				myfunction_thi = new MyFunctions_THI(getApplicationContext());
				jsonobject = myfunction_thi.loginUser(username, Oldpassword);
				thanhcong = jsonobject.toString();
			}

		} catch (Exception e) {
			edtOldPasswrod.setText("");
			edtOldPasswrod.setError("Password cũ không đúng");
			edtOldPasswrod.requestFocus();
			setEditTextFocus(edtOldPasswrod, true);
			isOk = false;
		}

		return isOk;

	}

	// kiem tra passwor moi
	public boolean checkPassWordAndConfirmPassword(String password,
			String confirmPassword) {
		boolean pstatus = false;
		password = edtmatkhaumoi.getText().toString().trim();
		confirmPassword = edtconfirmpassword.getText().toString().trim();
		if (confirmPassword != null && password != null) {
			if (password.equals(confirmPassword)) {
				pstatus = true;
			}
		}
		return pstatus;
	}

	public void showdate() {
		DatePickerDialog dpdialog = new DatePickerDialog(this,
				new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						// TODO Auto-generated method stub
						/*
						 * String ngay = dayOfMonth + "/" + (monthOfYear + 1) +
						 * "/" + year;
						 */
						String ngay = year + "-" + (monthOfYear + 1) + "-"
								+ dayOfMonth;
						switch (typengay) {
						case 1:
							tvBirthday.setText(ngay);
							break;

						}
					}
				}, lich.get(Calendar.YEAR), lich.get(Calendar.MONTH),
				lich.get(Calendar.DAY_OF_MONTH));
		dpdialog.show();
	}

	public boolean checkPassWord() {
		boolean isOk = true;

		if ((edtmatkhaumoi.length()) < 6) {
			edtmatkhaumoi.setError("Mat khau moi phai tu 6 ky tu tro len");
			edtmatkhaumoi.requestFocus();
			setEditTextFocus(edtmatkhaumoi, true);
			isOk = false;
		} else if (!checkPassWordAndConfirmPassword(edtmatkhaumoi.getText()
				.toString(), edtconfirmpassword.getText().toString()))

		{
			edtmatkhaumoi.setText("");
			edtconfirmpassword.setText("");
			edtmatkhaumoi.setError("Mật khẩu không trùng khớp");
			edtmatkhaumoi.requestFocus();
			setEditTextFocus(edtmatkhaumoi, true);
			isOk = false;
		} else if (tvBirthday.getText().toString().equals("")) {
			typengay = 1;
			isOk = false;
			showdate();
		}

		/*
		 * Person person = mPlusClient.getCurrentPerson(); if(person!=null &&
		 * person.hasBirthday()) { ngay = person.getBirthday(); } else {
		 * edtngaysinh.setError("ngay sinh khong dung"); }
		 */
		return isOk;
	}

	public boolean check() {
		boolean isOk = true;
		if (edtdangnhap.getText().toString().equals("")) {
			edtdangnhap.setError("Bạn Chưa Nhập Tên Đăng Nhập");
			edtdangnhap.requestFocus();
			setEditTextFocus(edtdangnhap, true);
			isOk = false;
		} else if ((edtdangnhap.length()) < 6) {
			edtdangnhap.setError("ten dang nhap phai lon hon  6 ky tu");
			edtdangnhap.requestFocus();
			setEditTextFocus(edtdangnhap, true);
			isOk = false;
		} else if (edtdiachimail.getText().toString().equals("")) {
			edtdiachimail.setError("Bạn Chưa Nhập Địa Chỉ Email");
			edtdiachimail.requestFocus();
			setEditTextFocus(edtdiachimail, true);
			isOk = false;
		} else if (!validateEmailAddress(edtdiachimail.getText().toString()
				.trim())) {
			edtdiachimail.setError("Địa Chỉ Email không đúng");
			edtdiachimail.requestFocus();
			setEditTextFocus(edtdiachimail, true);
			isOk = false;
		} else if (edtOldPasswrod.getText().toString().equals("")) {
			edtOldPasswrod.setError("Bạn Chưa Nhập Mật Khẩu");
			edtOldPasswrod.requestFocus();
			setEditTextFocus(edtOldPasswrod, true);
			isOk = false;
		} else if ((edtOldPasswrod.length()) < 6) {
			edtOldPasswrod.setError("Mat khau phai tu 6 ky tu tro len");
			edtOldPasswrod.requestFocus();
			setEditTextFocus(edtOldPasswrod, true);
			isOk = false;
		}
		if (tvBirthday.getText().toString().equals("")) {
			typengay = 1;
			isOk = false;
			showdate();
		}
		return isOk;
	}

	public void setEditTextFocus(EditText et, boolean isFocused) {
		et.setCursorVisible(isFocused);
		et.setFocusable(isFocused);
		et.setFocusableInTouchMode(isFocused);
		if (isFocused) {
			et.requestFocus();
		}
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
	}
}
